
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
use std::thread::JoinHandle;
/// # 线程池

///# 线程间传递消息类型的枚举
/// NewJob为新任务，Terminate为线程停止的信号
///
/// 当线程得到Terminate时线程会终止运行
enum Message {
    NewJob(Job),
    Terminate
}
/// ## Job实际为闭包
type Job = Box<dyn FnOnce() + Send + 'static>;

/// # 线程池对象
/// 线程池对象内部维护着工作对象，每个Worker维护着一个线程
///
/// 维护着一个mpsc::Sender对象，用于向各个线程发送消息
pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: mpsc::Sender<Message>
}

/// # 464646
impl ThreadPool {
    pub fn new(size: usize) -> Self {
        assert!(size > 0);
        let mut workers = Vec::with_capacity(size);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));
        for id in 0 .. size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }
        ThreadPool {
            workers,
            sender
        }
    }
    pub fn execute<F>(&self, f: F)
        where F: FnOnce() + Send + 'static {
        let job = Box::new(f);
        self.sender.send(Message::NewJob(job)).unwrap()
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        println!("send terminate for all workers...");
        for _ in &mut self.workers {
            self.sender.send(Message::Terminate).unwrap();
        }
        println!("shutdown all workers...");
        for worker in &mut self.workers {
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}

pub struct Worker {
    id: usize,
    thread: Option<JoinHandle<()>>
}

impl Worker {
    pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
        let thread = thread::spawn(move ||{
            loop {
                let message = receiver.lock().unwrap().recv().unwrap();
                match message {
                    Message::NewJob(job) => {
                        job();
                    },
                    Message::Terminate => {
                        break;
                    },
                }
            }
        });

        Worker {
            id,
            thread: Option::Some(thread)
        }
    }
}